
#include "string.h"

const size_t strlen(const char* string) 
{
    size_t len = 0; 
    while (string[len]) { 
        len++; 
    }

    return len; 
}

const size_t strnlen(const char* string, const size_t size)
{
    size_t len = 0; 
    while (string[len]) { 
        len++; 
        if (len >= size) {
            break; 
        }
    }

    return len; 
}

const size_t strnlen_terminator(const char* string, const size_t size, const char terminator)
{
    size_t len = 0; 
    while (string[len] && string[len] != terminator) { 
        len++; 
        if (len >= size) {
            break; 
        }
    }

    return len; 
}

const int to_numeric_digit(const char c) 
{
    return c - '0'; 
}

const int is_digit(const char c)
{
    return c >= '0' && c <= '9'; 
}

char* strcpy(char* dest, const char* src)
{
    char* tmp = dest; 
    while (*src != 0) {
        *dest = *src; 
        dest++;
        src++; 
    }

    *dest = 0; 
    return tmp; 
}

char* strncpy(char* dest, const char* src, size_t n)
{
    char* tmp = dest; 
    while (*src != 0 && n-- > 0) {
        *dest = *src; 
        dest++;
        src++; 
    }

    *dest = 0; 
    return tmp; 
}

const int strcmp(const char* str1, const char* str2)
{
    int u1, u2; 
    while (1) {
        u1 = (int)*str1++;
        u2 = (int)*str2++; 

        if (u1 != u2) {
            return u1 - u2; 
        }

        if (u1 == 0) {
            return 0; 
        }
    }

    return 0; 
}

const int strncmp(const char* str1, const char* str2, size_t n) 
{
    int u1, u2; 
    while (n-- > 0) {
        u1 = (int)*str1++;
        u2 = (int)*str2++; 

        if (u1 != u2) {
            return u1 - u2; 
        }

        if (u1 == 0) {
            return 0; 
        }
    }

    return 0; 
}

const char toupper(const char c)
{
    if (c >= 'a' && c <= 'z') {
        return c - 'a' + 'A'; 
    } 

    return c; 
}

const char tolower(const char c) 
{
    if (c >= 'A' && c <= 'Z') {
        return c - 'A' + 'a'; 
    }

    return c; 
}

const int istrcmp(const char* str1, const char* str2)
{
    int u1, u2; 
    while (1) {
        u1 = (int)tolower(*str1++);
        u2 = (int)tolower(*str2++); 

        if (u1 != u2) {
            return u1 - u2; 
        }

        if (u1 == 0) {
            return 0; 
        }
    }

    return 0; 
}

const int istrncmp(const char* str1, const char* str2, size_t n) 
{
    int u1, u2; 
    while (n-- > 0) {
        u1 = (int)tolower(*str1++);
        u2 = (int)tolower(*str2++); 

        if (u1 != u2) {
            return u1 - u2; 
        }

        if (u1 == 0) {
            return 0; 
        }
    }

    return 0; 
}


